import asyncio
import time

import aiofiles
import aiohttp
import execjs


async def main():
    ctx = execjs.compile(''' function ts () { return ~new Date(); } ''')
    async with aiohttp.ClientSession() as client:
        url = "https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&" \
              "redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new" \
              "&lang=zh_CN&_={}"
        timestamp = int(round(time.time() * 1000))
        async with client.get(url.format(timestamp)) as resp:
            txt = await resp.text()
            print(txt)
            arr = txt.split('= "')
            code = arr[1].replace('";', '', 1)
        #  二维码
        async with client.get('https://login.weixin.qq.com/qrcode/{}'.format(code)) as resp:
            async with aiofiles.open('wechat.jpg', mode='wb') as f:
                await f.write(await resp.content.read())

        # 获取登录链接
        url = 'https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={}&tip=1&r={}&_={}'
        url = url.format(code, ctx.call('ts'), timestamp)
        async with client.get(url) as rsp:
            txt = await rsp.text()
            print(txt)
            url = txt.split('window.redirect_uri="')[1].replace('";', '', 1)
            # 登录页面
            async with client.get(url) as resp:
                print(await resp.text())

            url = 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r={}&pass_ticket={}'
            url = url.format(ctx.call('ts'), "ticket_pass")
            async with client.get(url) as resp:
                print(await resp.text())


if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())
